<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Answer Class
 *
 * @category	Home
 */
class AnswerAction extends HomeAction
{

    protected $Answer;


	function _initialize()
	{
		parent::_initialize();
		$this->Answer = D('Answer');
	}


    /*
     *保存答案,答案有两种来源(1.正常回答问题 2.问题已解决,继续完善答案)
     */
    public function add()
    {
		
    	import('ORG.Net.Http');
		
    	$Team = D('Team');
    	$TeamUser = D('TeamUser');
    	$Question = D('Question');
    	$AnswerRevision = D('AnswerRevision');
    	
    	$qstID = intval($_REQUEST['qid']);
    	$question = $Question->find($qstID);
    	if (empty($question))
    	{
    		$this->error(L('question_not_existed'));
    	}
    	
    	$captcha = require_captcha_when('post', $this->_user['user_group']);

    	//检查用户权限
    	if (!$this->_userGroup['allow_answer'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	$isTeamwork = 0;

    	//检查是否已回答
    	if (!$this->_userGroup['allow_multiple_answer'])
    	{
    	    $map = array(
        		'question_id' => $qstID,
        		'poster_id'   => $this->_user['user_id'],
        	);
        	$count = $this->Answer->where($map)->count();
        	if ($count > 1)
        	{
        		$this->error(L('question_answered'));
        	}
    	}
    	
    	if (3 == $question['status'] && !$this->_userGroup['allow_answer_resolved_question'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	if ($this->isPost())
    	{
            //activity限制检查
        	if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'answer'))
        	{
        		$this->error(L('exceed_answer_limit'));
        	}

        	//内容长度检查
    		$minPostChars = $this->_global['min_post_chars'];
    		$maxPostChars = $this->_global['max_post_chars'];
    		if (strlen($_POST['details']) < $minPostChars)
    		{
    			$this->error(L('too_few_characters'));
    		}
    		if (strlen($_POST['details']) > $maxPostChars)
    		{
    			$this->error(L('too_much_characters'));
    		}

        	//链接数检查
        	if (exceed_link_limit($_POST['details']))
        	{
        		$this->error(L('too_much_links'));
        	}

        	//验证码检查
    		if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
    		{
    			$this->error(L('captcha_incorrect'));
    		}
    		
    		//内容过滤
        	if ($this->_global['word_censor_enable'])
        	{
        		$_POST['details'] = censor_text($_POST['details']);
        	}

        	//是否需要审核
        	if (!$this->_userGroup['allow_direct_post'])
        	{
        		$message = L('answer_require_approval');
        		$isVisible = 0;
        	}
        	else
        	{
        	    $message = L('answer_posted');
        		$isVisible = 1;
        	}
        	
        	$isImproved = 'improve' == $type ? 1 : 0;

        	//保存答案
        	$data = array(
        		'category_id'       => $question['category_id'],
        		'question_id'       => $question['question_id'],
        		'poster_id'         => $this->_user['user_id'],
        		'poster_name'       => $this->_user['username'],
        		'poster_ip'         => get_client_ip(),
        		'details'           => trim($_POST['details']),
        		'create_time'       => time(),
        		'is_visible'        => $isVisible,
        		'is_improved'       => $isImproved,
        		'markup_mode'       => $this->_global['markup_mode'],
        		'new_comment_alert' => intval($_POST['new_comment_alert']),
        	);

        	//团队合作编辑
        	$teamID = !empty($_POST['team_id']) ? intval($_POST['team_id']) : 0;
        	if (!empty($teamID))
        	{
        		$isTeamwork = 1;
        		$data['is_teamwork'] = 1;
        		$data['team_id'] = $teamID;
        		$data['team_name'] = $Team->getTeamNameByID($teamID);
        	}
        	$ansID = $this->Answer->add($data);
        	
        	//更新问题答案计数
        	$Question->updateAnswerCount($question['question_id']);
        	
        	//更新用户答案计数
    		$this->_User->setInc('answer_count', 'user_id='.$this->_user[user_id], 1);
    		
        	//更新用户积分以及动态
        	$type = 'answer';
        	$points = get_activity_points($type);
        	$this->_User->updatePointCount($this->_user['user_id'], $points);
        	$this->_User->logActivity($this->_user['user_id'], $type, $points, $qstID);
        	
    		if ($isTeamwork)
        	{
        		//团队编辑版本记录
        		$revision = array(
	    			'answer_id'   => $ansID,
	    			'editor_id'   => $data['poster_id'],
	    			'editor_name' => $data['poster_name'],
	    			'create_time' => time(),
	    			'details'     => $data['details'],  
	    		);
	    		$AnswerRevision->add($revision);
        		//更新团队答案计数
        		$Team->setInc('answer_count', 'team_id='.$teamID, 1);
        		//更新团队积分
        		$Team->updatePointCount($teamID, $points);
        	}

    		//新答案通知
    		if ($question['new_answer_alert'])
    		{
    			$requestUrl = get_site_domain(). U('Notification/newAnswerAlert', array('aid' => $ansID));
    			Http::async_request($requestUrl);
    		}
        	$this->success($message);
    	}
    	else
    	{
    		$teams = $TeamUser->getUserTeams($this->_user['user_id']);
    	    $teams = list_search($teams, array('category_id'=>$question['category_id']));
    	    if (!empty($teams))
    	    {
    	    	foreach ($teams as $key => $team)
    	    	{
    	    		$link = '<a href="'. format_team_url($team['team_id'], $team['name']) .'">'. $team['name'] .'</a>';
    	    		$teams[$key]['label'] = sprintf(L('answer_with_team'), $link);
    	    	}
    	    }
    	    
    	    $this->assign('teams', $teams);
    		$this->assign('question', $question);
    	    $this->assign('captcha', $captcha);
    	    $this->assign('type', $type);
    	    $html = $this->fetch();
    	    exit($html);
    	}
    }


    //编辑答案
    public function edit()
    {
		
    	$Question = D('Question');
    	$TeamUser = D('TeamUser');
    	$AnswerRevision = D('AnswerRevision');
    	
 		$ansID = intval($_REQUEST['aid']);
 		$answer = $this->Answer->find($ansID);
 		if (empty($answer))
 		{
 			$this->error(L('answer_not_existed'));
 		}

 		$question = $Question->find($answer['question_id']);
 		
 		$captcha = require_captcha_when('post', $this->_user['user_group']);
 		
 		//检查用户权限
 		$perms = array();
    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $answer['categroy_id']);
    	$perms['admin_edit_answer'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_edit_answer');
    	$perms['user_edit_answer']  = $this->_userGroup['allow_edit_answer'];
    	if ($answer['is_teamwork'])
    	{
    		$isTeamUser = $TeamUser->isTeamUser($this->_user['user_id'], $answer['team_id']);
    		$perms['user_edit_answer'] = $perms['user_edit_answer'] && $isTeamUser;
    	}
    	else 
    	{
    		$perms['user_edit_answer'] = $perms['user_edit_answer'] && $this->_user['user_id'] == $answer['poster_id'];
    	}
    	
    	if (!$perms['admin_edit_answer'] && !$perms['user_edit_answer'])
    	{
    		$this->error(L('no_perms_action'));
    	}

 		if ($this->isPost())
 		{
			//内容长度检查
    		$minPostChars = $this->_global['min_post_chars'];
    		$maxPostChars = $this->_global['max_post_chars'];
    		if (strlen($_POST['details']) < $minPostChars)
    		{
    			$this->error(L('too_few_characters'));
    		}
    		if (strlen($_POST['details']) > $maxPostChars)
    		{
    			$this->error(L('too_much_characters'));
    		}

            //验证码检查
    		if ($captcha && md5($_POST['verify']) != $_SESSION['verify'])
    		{
    			$this->error(L('captcha_incorrect'));
    		}

	    	//内容过滤
	    	if ($this->_global['word_censor_enable'])
	    	{
	    		$_POST['details'] = censor_text($_POST['details']);
	    	}

	    	$data = array(
	    		'details'           => trim($_POST['details']),
	    		'last_edit_time'    => time(),
	    		'last_editor_id'    => $this->_user['user_id'],
	    		'last_editor_name'  => $this->_user['username'],
	    		'new_comment_alert' => intval($_POST['new_comment_alert']),
	    	);
	    	$where = array('answer_id' => $ansID);
	    	$this->Answer->where($where)->save($data);
	    	
	    	//团队编辑版本记录
	    	if (md5($data['details']) != md5($answer['details']))
	    	{
	    		$revision = array(
		    		'answer_id'   => $ansID,
		    		'editor_id'   => $this->_user['user_id'],
		    		'editor_name' => $this->_user['username'],
		    		'create_time' => time(),
		    		'details'     => $data['details'],
		    	);
		    	$AnswerRevision->add($revision);
	    		$this->Answer->updateEditorCount($ansID);
	    	}
	    	$this->success(L('answer_edited'));
 		}
 		else
 		{
 			$revisions = array();
 			if ($answer['is_teamwork'])
 			{
 				$revisions = $AnswerRevision->getAnswerRevisions($ansID);
 			}
 			
 		    $this->assign('question', $question);
 			$this->assign('answer', $answer);
 			$this->assign('revisions', $revisions);
 			$this->assign('perms', $perms);
 			$this->assign('captcha', $captcha);
            $html = $this->fetch();
	    	exit($html);
 		}
    }


    //删除问题
    public function delete()
    {
    	
        $Question = D('Question');

    	$ansID = intval($_GET['aid']);
    	$answer = $this->Answer->find($ansID);
    	$question = $Question->find($answer['question_id']);

    	if (empty($answer))
    	{
    		$this->error(L('answer_not_existed'));
    	}

    	//检查用户权限
    	$perms = array();
    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $answer['category_id']);
    	$perms['allow_delete_answer'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_delete_answer');
    	$allow = ($this->_user['user_id'] == $answer['poster_id'] &&  $this->_userGroup['allow_delete_answer']) || $perms['allow_delete_answer'];
    	if (!$allow)
    	{
    		$this->error(L('no_perms_action'));
    	}

    	//更新用户积分
    	$type = 'delete_answer';
		$points = get_activity_points($type);
		$this->_User->updatePointCount($answer['poster_id'], $points);
		$this->_User->logActivity($answer['poster_id'], $type, $points, $ansID);

		//删除答案
		$this->Answer->deleteAnswerByID($ansID);

		//更新问题答案计数
		$Question->updateAnswerCount($question['question_id']);

		//记录版主操作记录
		if ($isModerator)
		{
			//todo
		}
		$url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }


    //挑选最佳答案
    public function chooseBestAnswer()
    {
    	
    	$Team = D('Team');
    	$Question = D('Question');
    	$Feedback = D('QuestionFeedback');

    	$ansID = intval($_REQUEST['aid']);

    	$answer = $this->Answer->find($ansID);
    	$question = $Question->find($answer['question_id']);
    	$qstID = $question['question_id'];

    	if (empty($answer))
    	{
    		$this->error(L('answer_not_existed'));
    	}

    	//检查用户权限
    	$allow = $this->_user['user_id'] == $question['poster_id'];
    	if (!$allow)
    	{
    		$this->error(L('no_perms_action'));
    	}

    	if ($this->isPost())
 		{
        	$where = array('answer_id' => $ansID);
        	$data = array('is_best' => 1);
        	$this->Answer->where($where)->save($data);

        	$data = array(
        		'status' => 3,
        		'resolve_time' => time(),
        	);
        	$where = array('question_id' => $qstID);
        	$Question->where($where)->save($data);

        	$data = array(
        	   'question_id' => intval($qstID),
        	   'poster_id'   => intval($this->_user['user_id']),
        	   'star_level'  => $_POST['star_level'] ? intval($_POST['star_level']) : 5,
        	   'details'     => trim($_POST['details']),
        	);
        	$Feedback->replace($data);

        	//归还提问者积分
        	$type = 'choose_best_answer';
        	$points = get_activity_points($type);
        	$this->_User->logActivity($this->_user['user_id'], $type, $points, $qstID);
        	$this->_User->updatePointCount($this->_user['user_id'], $points);

        	//奖励最佳回答者
        	$type = 'best_answer';
        	$points = 0;
        	$points += get_activity_points($type);
        	$points += $question['reward_point'];

    		$this->_User->logActivity($answer['poster_id'], $type, $points, $qstID);
    		$this->_User->updatePointCount($answer['poster_id'], $points);
    		$this->_User->setInc('best_answer_count', 'user_id='.$answer['poster_id'], 1);
    		
    		//奖励团队
    		if ($answer['is_teamwork'])
    		{
    			$Team->updatePointCount($answer['team_id'], $points);
    			$Team->setInc('best_answer_count', 'team_id='.$answer['team_id'], 1);
    		}

    		//最佳答案通知(通知回答者)
    		$answerer = $this->_User->find($answer['poster_id']);
    		if ($answerer['best_answer_alert'])
    		{
    			import('ORG.Net.Http');
    			$requestUrl = get_site_domain(). U('Notification/selectedAsBestAnswerAlert', array('aid' => $ansID));
    			Http::async_request($requestUrl);
    		}

    		$url = format_question_url($question['question_id'], $question['title']);
    		redirect($url);
 		}
 		else
 		{
 		    $this->assign('question', $question);
 		    $this->assign('answer', $answer);
 		    $html = $this->fetch();
 		    exit($html);
 		}
 	}


    //票选最佳答案
    public function voteBestAnswer()
    {
    	
    	$Question = D('Question');
    	$Activity = D('Activity');

    	$type = 'vote';
    	$qstID = intval($_GET['qid']);
    	$ansID = intval($_GET['aid']);

    	$question = $Question->find($qstID);
    	$answer = $this->Answer->find($ansID);

    	if (empty($question))
    	{
    		$this->error(L('question_not_existed'));
    	}

        if (empty($answer))
    	{
    		$this->error(L('answer_not_existed'));
    	}

    	//检查用户权限
    	if (!$this->_userGroup['allow_vote'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	//activity限制检查
    	if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], $type))
    	{
    		$this->error(L('exceed_vote_limit'));
    	}

    	$map = array(
    		'user_id'    => $this->_user['user_id'],
    		'type'       => $type,
    		'related_id' => $qstID,
    	);
    	$count = $Activity->where($map)->count();
    	if ($count > 0)
    	{
    		$this->error(L('answer_voted_already'));
    	}

    	//更新本答案投票计数
    	$this->Answer->setInc('vote_count', 'answer_id='.$ansID, 1);

    	//更新总投票计数
    	$Question->setInc('vote_count', 'question_id='.$qstID, 1);

    	//更新用户积分
    	$points = get_activity_points($type);
    	$this->_User->updatePointCount($this->_user['user_id'], $points);
    	$this->_User->logActivity($this->_user['user_id'], $type, $points, $qstID);

    	$url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }


    //投选无最佳答案
    public function voteNoBestAnswer()
    {
    	
        $Question = D('Question');
        $Activity = D('Activity');

        $type = 'vote';
    	$qstID = intval($_GET['qid']);
    	$question = $Question->find($qstID);

    	if (empty($question))
    	{
    		$this->error(L('question_not_existed'));
    	}

    	//用户权限检查
    	if (!$this->_userGroup['allow_vote'])
    	{
    		$this->error(L('no_perms_action'));
    	}

    	//activity限制检查
    	if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'vote'))
    	{
    		$this->error(L('exceed_vote_limit'));
    	}

    	$map = array(
    		'user_id'    => $this->_user['user_id'],
    		'type'       => $type,
    		'related_id' => $qstID,
    	);
    	$count = $Activity->where($map)->count();
    	if ($count > 0)
    	{
    		$this->error(L('answer_voted'));
    	}

    	//更新投票计数
    	$where = array('question_id' => $qstID);
    	$data = array(
    		'vote_count' => array('exp', 'vote_count+1'),
    		'no_best_vote_count' => array('exp', 'no_best_vote_count+1'),
    	);
    	$Question->where($where)->save($data);

    	//更新用户积分
    	$points = get_activity_points($type);
    	$this->_User->updatePointCount($this->_user['user_id'], $points);
    	$this->_User->logActivity($this->_user['user_id'], $type, $points, $qstID);

    	$url = format_question_url($question['question_id'], $question['title']);
        redirect($url);
    }

}
// End Class

/* End of file AnswerAction.class.php */
/* Location: ./App/Lib/Action/Home/AnswerAction.class.php */
